import { IBreadcrumb } from '@/base-ui/breadcrumb'
import { RouteRecordRaw } from 'vue-router'

let firstMenu: any = null

export function mapMenuToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  // 1.先加载默认的所有的routes
  const allRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('../router/main', true, /\.ts/)

  routeFiles.keys().forEach((key) => {
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })
  // 2.根据菜单获取需要添加的routes

  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) routes.push(route)
        if (!firstMenu) {
          firstMenu = menu
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }

  _recurseGetRoute(userMenus)

  return routes
}

export function pathMapBreadcrumbs(menus: any, currentPath: string): any {
  const breadcrumbItems: IBreadcrumb[] = []

  pathMapToMenu(menus, currentPath, breadcrumbItems)

  return breadcrumbItems
}

export function pathMapToMenu(
  menus: any,
  currentPath: string,
  breadcrumbs?: IBreadcrumb[]
): any {
  for (const menu of menus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name })
        breadcrumbs?.push({ name: findMenu.name })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

export function mapMenusToPermissions(menus: any[]) {
  const permissionMenus: any[] = []

  const _recurseGetPermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? [])
      } else if (menu.type === 3) {
        permissionMenus.push(menu.permission)
      }
    }
  }

  _recurseGetPermission(menus)

  return permissionMenus
}

export function menuMapLeafKeys(menusList: any[]) {
  const leafList: number[] = []

  const _recurseGetLeafItem = (menus: any[]) => {
    for (const item of menus) {
      if (item.children) {
        _recurseGetLeafItem(item.children)
      } else {
        leafList.push(item.id)
      }
    }
  }
  _recurseGetLeafItem(menusList)

  return leafList
}

export { firstMenu }
